﻿using backend.Entity;
using backend.Enum;
using backend.Models;
using backend.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace backend.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly MyContext _context;

        public AccountController(MyContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 管理员首次注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public MyJsonResult Register(RegisterModel model)
        {
            if (_context.Users.Any())
            {
                return MyJsonResult.Error("管理员已存在,不可注册");
            }

            User u = new User();
            u.Name = model.name;
            u.UserName = model.username;
            u.Pwd = MD5Helper.Get32MD5(u.UserName + model.pwd);
            u.Role = RoleType.Manager;

            MyJsonResult result = null;
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    _context.Users.Add(u);

                    _context.SaveChanges();
                    tran.Commit();
                    result = MyJsonResult.Ok(u);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    result = MyJsonResult.Error(ex.Message);
                }
            }
            return result;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public MyJsonResult Login(LoginModel model)
        {
            // 根据用户名查询用户
            User user = _context.Users.SingleOrDefault(a => a.UserName == model.UserName);
            if (user == null)
            {
                return MyJsonResult.Error("用户不存在");
            }
            if (MD5Helper.Get32MD5(user.UserName + model.Password) != user.Pwd)
            {
                return MyJsonResult.Error("密码错误");
            }
            return MyJsonResult.Ok(new { user = user, token = TokenHelper.Instance().GenerateToken(user.UserName, user.Role) });
        }

        // PUT api/account/changePwd
        /// <summary>
        /// 修改个人密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        [Authorize]
        public async Task<MyJsonResult> ChangePwd(PwdModel model)
        {
            User current = _context.Users.FirstOrDefault(a => a.UserName == this.User.Identity.Name);
            if (current == null)
            {
                return MyJsonResult.Error("用户信息不存在");
            }
            current.Pwd = MD5Helper.Get32MD5(current.UserName + model.Pwd);
            _context.Users.Update(current);
            await _context.SaveChangesAsync();
            return MyJsonResult.Ok(current);
        }
    }
}
